#include <intrins.h>
#include <stdio.h>
#include <string.h>
#include "framework.h"



#if defined(NUVOTON)
	//use uart0
	//#define PIN_INIT()												MODIFY_HIRC_166();P06_PushPull_Mode();P07_Input_Mode();
	
	//use uart1
	#define PIN_INIT()												MODIFY_HIRC_166();P16_PushPull_Mode();P02_Input_Mode();
#elif defined(STC)
	#if defined(STC8A)
		#define PIN_INIT()											P1M1 = 0x01;P1M0 = 0xfe
	#elif defined(STC8G)
		#define PIN_INIT()											P0M1 = 0x05;P0M0 = 0xfa;P1M1 = 0x01;P1M0 = 0xfe;
	#elif defined(STC8H)
		#define PIN_INIT()											P1M1 = 0x01;P1M0 = 0xfe
	#endif
#elif defined(SINONE)
	#define PIN_INIT()											
#endif
														


					
																				

#define USER_CONFIG()								PIN_INIT()



//------------------------------------------AD------------------------------------------------
#define AD_CHANNEL_INTERNAL_BOND_GAP								8
//--------------------------------------------------------------------------------------------


//--------------------------------------EVENT-------------------------------------------------
#define EVENT_SHOW_MESSAGE													0x0100
#define EVENT_AD_RESULT															0x0200
//--------------------------------------------------------------------------------------------


//--------------------------------------soft timers--------------------------------------------
//soft timer id
#define SOFT_TIMER_SHOW_MESSAGE										0


//--------------------------------------soft timer interval------------------------------------
//soft timer interval
#define SHOW_MESSAGE_INTERVAL											1000		//ms
//---------------------------------------------------------------------------------------------



#define VERSION_MESSAGE "Programme starts! Designed by zhenhuanchn@qq.com, build on " __TIME__ "," __DATE__ "\r\n"


unsigned long ad_count = 0;
unsigned long ad_sum = 0;


char putchar (char ch)
{
	uart1_write(&ch, sizeof(ch));
	return ch;
}


void core_timer_routine()
{
	SOFT_TIMER_PULSE();
}


void on_ad_result()
{
	unsigned int ad = ad_get_result();

	ad_sum += ad;
	ad_count++;
	ad_measure(AD_CHANNEL_INTERNAL_BOND_GAP);
}
	

void on_show_message()
{
	printf("ad count [%ld], average value [%ld]\r\n", ad_count, ad_sum/ad_count);
	ad_count = 0;
	ad_sum = 0;

	soft_timer_start(SOFT_TIMER_SHOW_MESSAGE, SHOW_MESSAGE_INTERVAL);	
}


void main(void)
{
	USER_CONFIG();
	timer0_init(TIMER_LOAD_VALUE16(0.001,FOSC,12), core_timer_routine);
	uart1_init(115200, 0, 0);
	ad_init(EVENT_AD_RESULT);
	
	INTERRUPT_ENABLE();
	timer0_start();
	
	printf(VERSION_MESSAGE);
	
	event_register(EVENT_AD_RESULT, on_ad_result);
	event_register(EVENT_SHOW_MESSAGE, on_show_message);
	soft_timer_manual_register(SOFT_TIMER_SHOW_MESSAGE, EVENT_SHOW_MESSAGE);
	soft_timer_start(SOFT_TIMER_SHOW_MESSAGE, SHOW_MESSAGE_INTERVAL);
	ad_measure(AD_CHANNEL_INTERNAL_BOND_GAP);
	
	
	for(;;)
	{
		event_pull();
		soft_timer_pull();
	}
}


